package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;

@Controller
@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
public class AreaAction extends BaseAction<Area>{

	@Autowired
    private AreaService areaService;

	//分页查询
	@Action(value="area_search",results={@Result(name="success",type="json")})
	public String findByQuery() {
		Pageable pageable=new PageRequest(page-1, rows);
		
		//对于页面查询的参数进行判断
		
		Specification<Area> specification =new Specification<Area>() {
			@Override
			public Predicate toPredicate(Root<Area> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				//判断省province
				List<Predicate> predicates=new ArrayList<Predicate>();
				if (StringUtils.isNotBlank(model.getProvince())) {
					Predicate p1 = cb.like(root.get("province").as(String.class), "%"+model.getProvince()+"%");
				    predicates.add(p1);
				}
				//判断市String city
				if (StringUtils.isNotBlank(model.getCity())) {
				 	Predicate p2 = cb.like(root.get("city").as(String.class), "%"+model.getCity()+"%");
			        predicates.add(p2);
				}
				//判断区 String district
				if (StringUtils.isNotBlank(model.getDistrict())) {
					Predicate p3 = cb.like(root.get("district").as(String.class), "%"+model.getDistrict()+"%");
				    predicates.add(p3);
				}
				
				Predicate predicate = cb.and(predicates.toArray(new Predicate[0]));
				return predicate;
			}
		};
		
		Page<Area> page=areaService.findByQuery(specification,pageable);
		
		pushPageDataToValueStack(page);
		return SUCCESS;
	}
	
	//区域的保存
	@Action(value="area_save",results={@Result(name="success",type="redirect",location="./pages/base/area.html")})
	public String save() {
		areaService.save(model);
		return SUCCESS;
			
	}
	
	//接收上传问价
	private File file;
	
	public void setFile(File file) {
		this.file = file;
	}

	//一件文件上传
	@Action(value="area_batchImport")
	public String batchImport() throws  IOException {
		//struts2文件上传是基于过滤器uploadFilter实现的
		//解析文件xls/xlsx
		//97-07解析xls格式用HSSF
		//07以后解析用xlsx格式用XSSF
		
		//编写解析代码，基于xls的解析
		List<Area> areas=new ArrayList<Area>();
		//加载解析对象，
		HSSFWorkbook hssfWorkbook=new HSSFWorkbook(new FileInputStream(file));
		//对取一个sheet,一个Excle中会有一个或者多个sheet
		HSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);
		//对取sheet里面的每一行数据
		for (Row row : sheetAt) {
			//每一行数据就相当对一个区域的对象，而且第一行一般是表头
			if (row.getRowNum()==0) {
				continue;
			}
			//跳过空行
			if (row.getCell(0)==null) {
				continue;
			}
			Area area=new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			
			//基于pinyin4j生成城市编码和简码
			
			//获得省市区的名称
			String province = area.getProvince().substring(0, area.getProvince().length()-1);
			String city = area.getCity().substring(0, area.getCity().length()-1);
			String district = area.getDistrict().substring(0,area.getDistrict().length()-1);
			//获取简码
			String[] headArr = PinYin4jUtils.getHeadByString(province+city+district);
			//拼接成字符串
			StringBuffer sb=new StringBuffer();
			for (String string : headArr) {
				sb.append(string);
			}
			String shortcode=sb.toString();
			area.setShortcode(shortcode);
			//获得编码
			String citycode = PinYin4jUtils.hanziToPinyin(city);
			area.setCitycode(citycode);
			//将每一个对象封装起来放入到集合中存储
			areas.add(area);
		}
		//调用业务层将其进行存储
		areaService.saveBatch(areas);
		return NONE;
	}
	
	//区域的作废
	@Action(value="area_delflag",results={@Result(name="success",type="redirect",location="./pages/base/area.html")})
	public String updateDelflag() {
		areaService.updateDelflag(tag,ids);
		return SUCCESS;
		
	}
	
	//查询所有区域
	@Action(value="area_findAll",results={@Result(name="success",type="json")})
	public String  areafindAll() {
		List<Area> areas=areaService.areafindAll();
		ActionContext.getContext().getValueStack().push(areas);
		return SUCCESS;
	}
	
}
